var optType = 1, optIndex = 0, optRow = null,
    index = 1, size = 20, key = '',
    pager = null;

var config = {
    table: {
        toolbar:'#table-auth-btn',
        pageSize: size,
        onClickRow:function () {
            optRow = component.datagrid.getRowData('#table-list');
            optIndex = component.datagrid.getDataRow('#table-list');
        },
        frozenColumns:[
            [
                {field:'loginName',title:'登录账号', align:'center',width:150 }
            ]
        ],
        columns:[
            [
                {field:'label',title:'数据标签', align:'left',
                    formatter:function (val, row, index) {
                        var label = '';
                        try{
                            $.each(val, function (index, obj) {
                                label += '[<a href="#" data-code="'+obj.code+'" ondblclick="opt.info(this);" class="easyui-linkbutton" data-options="plain:true">'+obj.name+'</a>]&nbsp;'
                            })
                        }catch (ex){}
                        return label;
                    }
                },
                {field:'status',title:'状态', align:'center',
                    formatter:function (val, row, index) {
                        switch (parseInt(val)){
                            case 0:
                                return '<a href="#" style="color:red;" onclick="opt.lock('+val+');">冻结</a>'
                            case 1:
                                return '<a href="#" style="color:green;" onclick="opt.lock('+val+');">启用</a>'
                        }
                    }
                },
                {field:'role',title:'角色', align:'left',
                    formatter:function (val, row, index) {
                        var roleData = store.get('sys-common-role');
                        var txt = '';
                        if(val.length > 0){
                            $.each(val, function (j, v) {
                                $.each(roleData, function (i, role) {
                                    if(role.id == v){
                                        txt += '['+role.name+']&nbsp; ';
                                    }
                                })
                            })
                            return txt;
                        }else{
                            return '<span style="color:red;">尚未配置角色</span>';
                        }
                    }
                }
            ]
        ]
    },
    form: {
        title: '用户管理',
        width:450,
        height:245,
        buttons: [{
            text:'保 存',
            iconCls:'icon-accept icon16',
            handler:function(){
                switch (optType){
                    case 1:
                        action.add();
                        break;
                    case 2:
                        action.edit();
                        break;
                }
            }
        },{
            iconCls:'icon-cancel icon16',
            text:'关 闭',
            handler:function(){
                component.dialog.close('#opt-form');
            }
        }]
    },
    role: {
        title: '用户角色管理',
        width:450,
        height:200,
        buttons: [{
            text:'保 存',
            iconCls:'icon-accept icon16',
            handler:function(){
                action.role();
            }
        },{
            iconCls:'icon-cancel icon16',
            text:'关 闭',
            handler:function(){
                component.dialog.close('#opt-form-role');
            }
        }]
    },
    label: {
        width:500,
        height:400,
        left: (kit.wh().width - 500) / 2
    },
}
$(function () {
    action.get();

})

var opt = {
    add: function (_event) {
        optType = 1;
        component.dialog.init('#opt-form', config.form);
        component.dialog.open('#opt-form');
        kit.form.clean('#opt-form-data');
    },
    delete: function () {
        if(optRow == null){
            kit.alert('请先选择一条数据', 'warning');
            return false;
        }
        var fun = "action.delete();";
        var c = {title: '不可逆操作', message: '确定要删除这个用户吗？', submit: fun }
        kit.confirm(c);
    },
    info: function (_event) {
        var label = optRow.label;
        var model = getCodeForLabel(label, kit.getAttr(_event, 'data-code'));
        var _height = model.children.length * 60;
        config.label.title = model.name;
        config.label.height = _height > 400 ? 400 : _height;
        component.dialog.init('#opt-form-label', config.label);
        component.dialog.open('#opt-form-label');
        initLableTable(model.children);
    },
    lock:function (_status) {
        var fun = "action.lock();";
        var c = {title: '删除权限',submit: fun }
        if(_status == 0){
            c.message = '是否将用户状态调整为[启用]状态？';
        }else{
            c.message = '是否将用户状态调整为[冻结]状态？';
        }
        kit.confirm(c);
    },
    auth:function (_event) {
        component.dialog.init('#opt-form-role', config.role);
        component.dialog.open('#opt-form-role');
        component.combobox.init2('#user-role', store.get('sys-common-role'), 'id');
        $('#user-role').combobox('setValues', optRow.role);
    },
    initPwd:function (_event) {
        if(optRow == null){
            kit.alert('请先选择一条数据', 'warning');
            return false;
        }
        var fun = "action.initPwd();";
        var c = {title: '温馨提示', message: '确定要重置这个用户的登录密码吗？', submit: fun }
        kit.confirm(c);
    },
    search:function (_event) {
        var obj = kit.form.get('#query-form');
        key = JSON.stringify(obj);
        if($.trim(obj.loginName).length == 0
            && $.trim(obj.userName).length == 0
            && $.trim(obj.phone).length == 0
            && $.trim(obj.sex).length == 0){
            key = '';
            index = 1;
            action.get();
        }else{
            index = 1;
            action.get();
        }
    },
    refresh:function () {
        kit.form.clean('#query-form');
        $('#query-sex').combobox('setValue', '');
        index = 1;
        key = '';
        action.get();
    }
}
var action = {
    get: function () {
        var param = {
            url: constant.route.user.base + '/' + index + '-' + size + '-' + key
        };
        var request = http.get(param);
        request.done(function (d) {
            config.table.data = d.result;
            component.datagrid.init('#table-list', config.table);
            pager = component.datagrid.getPager('#table-list');
            pager.pagination({
                onSelectPage:function (pageNumber, pageSize) {
                    index = pageNumber;
                    size = pageSize;
                    action.page();
                },
                onBeforeRefresh:function (pageNumber, pageSize) {
                    action.page();
                }
            })
        })
    },
    page:function () {
        var param = {
            url: constant.route.user.base + '/' + index + '-' + size + '-' + key
        };
        var request = http.get(param);
        request.done(function (d) {
            config.table.data = d.result;
            component.datagrid.load('#table-list', d.result);
        })
    },
    add: function () {
        var data = kit.form.get('#opt-form #opt-form-data');
        if($.trim(data.loginName).length < 5 || $.trim(data.loginName).length >= 20){
            kit.alert('登录账号长度必须在6个字符以上20个字符以下', 'warning');
            return false;
        }
        if($.trim(data.password).length < 5 || $.trim(data.password).length >= 20){
            kit.alert('登录密码长度必须在6个字符以上20个字符以下', 'warning');
            return false;
        }
        if(data.password != data.password2){
            kit.alert('您输入的2次密码不一致', 'warning');
            return false;
        }
        var param = {
            url: constant.route.user.base,
            data: data
        };
        var request = http.post(param);
        request.done(function (d) {
            var data = d.result;
            kit.form.clean('#opt-form-data');
            kit.alert(d.message, 'success');
            component.datagrid.append('#table-list', data);
        })
    },
    delete: function () {
        var param = {
            url: constant.route.user.base + '/' + optRow.id
        }
        var request = http.delete(param);
        request.done(function (d) {
            kit.alert(d.message, 'success');
            component.datagrid.deleteRow('#table-list', optIndex);
            optRow = null;
        })
    },
    lock: function () {
        var param = {
            url: constant.route.user.base + '/status/' + optRow.id
        };
        var request = http.put(param);
        request.done(function (d) {
            kit.alert(d.message, 'success');
            optRow.status = optRow.status == 0 ? 1 : 0;
            component.datagrid.updateRow('#table-list', optIndex, optRow);
        })
    },
    role:function () {
        var data = {userId: optRow.id};
        var roles = $('#user-role').combobox('getValues');
        data['roleIds'] = roles;
        optRow.role = roles;
        var param = {
            url: constant.route.user.base + '/role',
            data: data
        };
        var request = http.put(param);
        request.done(function (d) {
            component.dialog.close('#opt-form-role');
            kit.alert(d.message, 'success');
            component.datagrid.updateRow('#table-list', optIndex, optRow);
        })


    },
    initPwd:function () {
        var param = {
            url: constant.route.user.base + '/password/' + optRow.id
        };
        var request = http.put(param);
        request.done(function (d) {
            kit.alert(d.message, 'success');
        })
    }
}

function getCodeForLabel(_json, _code) {
    var obj = {};
    $.each(_json, function (i, o) {
        if(o.code == _code){
            obj = o;
        }
    })
    return obj;
}
function initLableTable(_obj) {
    var label = {
        title:'',
        data: _obj,
        pagination: false,
        onDblClickCell: onClickCell,
        onBeforeEdit:function(index,row){
            add()
        },
        columns:[
            [
                {field:'name',title:'属性', align:'center'},
                {field:'val',title:'数据', align:'left', width:200,
                    formatter:function (val, row, index) {
                        try{
                            if(row.type == 9){
                                var options = row.options;
                                var txt = '';
                                $.each(options, function (index, obj) {
                                    if(val == obj.val){
                                        txt = obj.txt;
                                    }
                                })
                                return txt;
                            }else{
                                return val;
                            }
                        }catch (ex){
                            return val;
                        }
                    }
                }
            ]
        ]
    };
    component.datagrid.init('#table-list-label', label);
    // 扩展
    $.extend($.fn.datagrid.methods, {
        addEditor : function(jq, param) {
            if (param instanceof Array) {
                $.each(param, function(index, item) {
                    var e = $(jq).datagrid('getColumnOption', item.field);
                    e.editor = item.editor;
                });
            } else {
                var e = $(jq).datagrid('getColumnOption', param.field);
                e.editor = param.editor;
            }
        },
        removeEditor : function(jq, param) {
            if (param instanceof Array) {
                $.each(param, function(index, item) {
                    var e = $(jq).datagrid('getColumnOption', item);
                    e.editor = {};
                });
            } else {
                var e = $(jq).datagrid('getColumnOption', param);
                e.editor = {};
            }
        },
        editCell: function(jq,param){
            return jq.each(function(){
                var opts = $(this).datagrid('options');
                var fields = $(this).datagrid('getColumnFields',true).concat($(this).datagrid('getColumnFields'));
                for(var i=0; i<fields.length; i++){
                    var col = $(this).datagrid('getColumnOption', fields[i]);
                    col.editor1 = col.editor;
                    if (fields[i] != param.field){
                        col.editor = null;
                    }
                }
                $(this).datagrid('beginEdit', param.index);
                for(var i=0; i<fields.length; i++){
                    var col = $(this).datagrid('getColumnOption', fields[i]);
                    col.editor = col.editor1;
                }
            });
        },
        datetimebox: {
            init: function (container, options) {
                var input = $('<input type="text" class="easyui-datetimebox">')
                    .appendTo(container);
                //编辑框延迟加载
                window.setTimeout(function () {
                    input.datetimebox($.extend({ editable: false }, options));
                }, 10);
                return input;
            },
            getValue: function (target) {
                return $(target).datetimebox('getValue');
            },
            setValue: function (target, value) {
                $(target).val(value);
                window.setTimeout(function () {
                    $(target).datetimebox('setValue', value);
                }, 150);
            },
            resize: function (target, width) {
                var input = $(target);
                if ($.boxModel == true) {
                    input.width(width - (input.outerWidth() - input.width()));
                } else {
                    input.width(width);
                }
            }
        }
    });

}

var editIndex = undefined;
function endEditing(){
    if (editIndex == undefined){return true}
    if ($('#table-list-label').datagrid('validateRow', editIndex)){
        $('#table-list-label').datagrid('endEdit', editIndex);
        editIndex = undefined;
        return true;
    } else {
        return false;
    }
}
function onClickCell(index, field){
    if (endEditing()){
        $('#table-list-label').datagrid('selectRow', index)
            .datagrid('editCell', {index:index,field:field});
        editIndex = index;
        var currentEdatagrid = $(this);
        var $input = $('.datagrid-editable .textbox,.datagrid-editable .datagrid-editable-input,.datagrid-editable .textbox-text');
        var oldRow = $('#table-list-label').datagrid('getSelected');

        $input.focus();
        $input.bind('keydown', function(e){
            var code = e.keyCode || e.which;
            if(code == 13){
                var row = $('#table-list-label').datagrid('getSelected');
                $(currentEdatagrid).datagrid('acceptChanges');
                $(currentEdatagrid).datagrid('endEdit', index);
                var data = {
                    userId: optRow.id,
                    labelId: row.id,
                    val: row.val
                }
                var param = {
                    url: constant.route.user.label,
                    data: data
                };
                var request = http.put(param);
                request.done(function (d) {})
            }
        });
        $input.focusout(function () {
            $(currentEdatagrid).datagrid('acceptChanges');
            $(currentEdatagrid).datagrid('endEdit', index);
            $(currentEdatagrid).datagrid('updateRow', index, oldRow);
        })

    }else{
        $('#table-list-label').datagrid('selectRow', editIndex);
    }
}
function remove(){
    $("#table-list-label").datagrid('removeEditor', 'val');
}
function add(){
    var row = $('#table-list-label').datagrid('getSelected');
    switch (row.type){
        case 1:
            $("#table-list-label").datagrid('addEditor', {
                field : 'val',
                editor : {
                    type : 'text'
                }
            });
            break;
        case 2:
            $("#table-list-label").datagrid('addEditor', {
                field : 'val',
                editor : {
                    type : 'numberbox'
                }
            });
            break;
        case 3:
            $("#table-list-label").datagrid('addEditor', {
                field : 'val',
                editor : {
                    type : 'datebox'
                }
            });
            break;
        case 9:
            $("#table-list-label").datagrid('addEditor', {
                field : 'val',
                editor : {
                    type : 'combobox',
                    options : {
                        data: row.options,
                        valueField: 'val',
                        textField: 'txt',
                        editable: false,
                        required : true
                    }
                }
            });
            break;
    }

}